import { login } from '@/services/ant-design-pro/api';
// import { getFakeCaptcha } from "@/services/ant-design-pro/login";
import { LockOutlined, MobileOutlined, UserOutlined } from '@ant-design/icons';
import {
  LoginForm,
  ProFormCaptcha,
  ProFormCheckbox,
  ProFormText,
} from '@ant-design/pro-components';
import { Form, RadioChangeEvent } from 'antd';
import { Alert, Card, message, Radio, Tabs } from 'antd';
import React, { useState } from 'react';
import type { Dispatch } from 'umi';
import { connect, history, useModel } from 'umi';
import styles from '../index.less';
import { useMutation } from 'react-apollo';
import {
  LOGIN_LoginWithPassword,
  LOGIN_phoneLoginWithCode,
  LOGIN_requestVerifyCode,
  USER_resetPasswordVerifyCode,
  USER_ResetPassword,
  USER_UserLogOut,
  LOGIN_userPhoneLogin,
  USER_resetPasswordVerifyCodeList,
} from '@/graphql';
import md5 from 'md5';
import { captchaStyle } from '../../../../config/globalStyle';
import moment from 'moment';
import { catchErrorMsg } from '@/uitls/utils';
import SelectRole from './selectRole';
export interface VerifyCode {
  (phone: string, VerifyType?: string): void;
}
const LoginMessage: React.FC<{
  content: string;
}> = ({ content }) => (
  <Alert
    style={{
      marginBottom: 24,
    }}
    message={content}
    type="error"
    showIcon
  />
);
const Login = ({ dispatch }: { dispatch: Dispatch }) => {
  const [isOpenSelectRole, setIsOpenSelectRole] = useState(false); // 选择角色的弹窗
  const [SelectRoleList, setSelectRoleList] = useState<any[]>([]);
  const [SelectedRole, setSelectedRole] = useState<any>(null); // 选中的身份
  const [userLoginState, setUserLoginState] = useState<API.LoginResult>({});
  const [type, setType] = useState<string>('account');
  const [roleType, setRoleType] = useState(3); // 1：管理员 2: 学生 3: 老师 4: 家长
  // 默认应该是老师
  // 管理员是另外提供的账号不是注册的 所以需要首次登录验证
  const { initialState, setInitialState } = useModel('@@initialState');
  const [verifyCode, setVerifyCode] = useState(''); // 验证码登录用的验证码
  const [phone, setPhone] = useState('');
  const [requestLoginVerifyCode, requestLoginVerifyCodeResult] =
    useMutation(LOGIN_requestVerifyCode);
  const [resetPasswordVerifyCode, resetPasswordVerifyCodeResult] = useMutation(
    USER_resetPasswordVerifyCode,
  );
  const [resetPasswordVerifyCodeList, resetPasswordVerifyCodeListResult] = useMutation(
    USER_resetPasswordVerifyCodeList,
  );
  const [phoneLoginWithCode, phoneLoginWithCodeResult] = useMutation(LOGIN_phoneLoginWithCode);
  const [ResetPassword, ResetPasswordResult] = useMutation(USER_ResetPassword);
  const [UserLogOut] = useMutation(USER_UserLogOut);
  const [userPhoneLogin] = useMutation(LOGIN_userPhoneLogin);
  const [LoginWithPassword, LoginWithPasswordResult] = useMutation(LOGIN_LoginWithPassword);
  // 通过下面注释的这种方式能够拿到错误 直接 {error, loading, data }是拿不到的
  // const { data, error } = LoginWithPasswordResult;
  // console.log(error?.networkError?.result);
  // console.log(LoginWithPasswordResult);

  //选择用色
  const SelectRoleProps = {
    isOpenSelectRole,
    list: SelectRoleList,
    handleOkSelectRole: (newData: any) => {
      setSelectedRole(newData);
      setIsOpenSelectRole(false);
      console.log('use 了父亲, get value:', newData);
      // 第在第一步获取到的数据里，拿取返回的id值，进行重置密码，则需要另外传入id值
    },
    handleCancelSelectRole: () => setIsOpenSelectRole(false),
  };

  // 重置密码
  const handleResetPassword = async (params: {
    forgetpassword?: string;
    mobile?: string;
    captcha?: string;
  }) => {
    // eslint-disable-next-line @typescript-eslint/no-shadow
    const { mobile, forgetpassword, captcha } = params;
    console.log(mobile, forgetpassword, captcha, params);

    try {
      const { data } = await ResetPassword({
        variables: {
          input: { phone: mobile, verifyCode: captcha, password: md5(forgetpassword!) },
        },
      });
      return data;
    } catch (error) {
      console.log(error);
      return message.error('重置失败，验证码错误或不存在');
    }
  };
  // 复用忘记密码和登录
  const handleVerifyCode: VerifyCode = async (phoneValue, VerifyType) => {
    console.log(VerifyType);

    const params = {
      variables: { input: { phone: phoneValue } },
    };
    try {
      const mockFlag = false;
      let data;
      if (mockFlag) {
        // mock data
        data = {
          data: {
            userRequestResetPasswordVerifyCode: {
              userList: [
                { id: 'VXNlcjoxNw==', name: 'think' },
                { id: 'VXNlcjoyNw==', name: 'think' },
                { id: 'VXNlcjoyOA==', name: 'think Teacher2' },
              ],
            },
          },
        };
      } else {
        data =
          VerifyType === 'login'
            ? await requestLoginVerifyCode(params)
            : await resetPasswordVerifyCodeList(params);
        console.log('result', data);
        if (data === false) {
          return;
        }
      }

      const dataList = (data as any)?.data.userRequestResetPasswordVerifyCode.userList;
      if (VerifyType === 'resetpassword' && dataList) {
        setIsOpenSelectRole(true);
        setSelectRoleList(dataList);
        return;
      }
      message.success('获取验证码成功！');
      return data;
    } catch (e) {
      console.log(e);
      const err =
        VerifyType === 'login'
          ? catchErrorMsg(requestLoginVerifyCodeResult)
          : catchErrorMsg(resetPasswordVerifyCodeListResult);
      message.error(err);
      return;
    }
  };

  const handlePhoneLoginWithCode = async (params: {
    type?: string;
    mobile?: string;
    captcha?: string;
  }) => {
    // eslint-disable-next-line @typescript-eslint/no-shadow
    const { mobile, type, captcha } = params;
    try {
      const { data } = await phoneLoginWithCode({
        variables: { input: { phone: mobile, verifyCode: captcha, type: type } },
      });
      return data;
    } catch (error) {
      console.log(error);
      return message.error('重置失败');
    }
  };

  const onChange = (e: RadioChangeEvent) => {
    console.log('radio checked', e.target.value);
    setRoleType(e.target.value);
  };
  const handleForgetPassword = () => {
    setType('forgetPassword');
    console.log('forget');
  };
  const handleVerifyCodeChange = (e: React.ChangeEvent<HTMLInputElement | HTMLTextAreaElement>) => {
    console.log(e);
    setVerifyCode(e.target.value);
  };
  const handlePhoneChange = (e: React.ChangeEvent<HTMLInputElement | HTMLTextAreaElement>) => {
    setPhone(e.target.value);
  };
  const fetchUserInfoMock = async () => {
    const userInfo = await initialState?.fetchUserInfo?.();
    if (userInfo) {
      await setInitialState((s) => ({
        ...s,
        currentUser: userInfo,
      }));
    }
  };
  const handleSubmit = async (values: API.LoginParams) => {
    let msg;
    const mockFlag = false;
    try {
      // 用graphql的

      // 账号密码登陆
      if (type === 'account' && !mockFlag) {
        // try {
        const res = await LoginWithPassword({
          variables: {
            input: {
              phone: values.username,
              password: md5(values.password!),
              roleType,
              type: 'PASSWORD',
            },
          },
        });
        const userId = res.data.userPhoneLogin.user.id;
        // 第二步：拿取userList中对应用户id值，进行id登录
        console.log(userId);

        await UserLogOut(); // 暂时先这么做 主要第一步登录之后会显示已登录 阻止了第二部的登录
        const res2 = await userPhoneLogin({
          variables: {
            input: {
              phone: values.username,
              type: 'ID',
              id: userId,
            },
          },
        });
        console.log('msg', userId, res2);
        const userData = res2.data.userPhoneLogin.user;
        console.log('userData', userData);
        if (userData) {
          message.success('登录成功');
          localStorage.setItem('userInfo', JSON.stringify(userData));
          const loginTime = moment(new Date()).format('YYYY/MM/DD HH:mm');
          localStorage.setItem('loginTime', loginTime);
          dispatch({
            type: 'user/setUserInfo',
            payload: {
              role: roleType,
              name: userData.name,
            },
          });
          history.push('/welcome');
        }

        return;
        // } catch (error) {
        //   const err = (LoginWithPasswordResult?.error?.networkError as any)?.result?.errors[0]
        //     .message;
        //   console.log(err, error);
        //   // message.error(err);
        //   // return;
        // }
      }
      // 验证码登陆
      if (type === 'VERIFY_CODE') {
        try {
          msg = await phoneLoginWithCode({
            variables: {
              input: {
                phone,
                verifyCode,
                roleType,
                type: type, // 'VERIFY_CODE'
              },
            },
          });
          console.log('msg', msg);
          return;
        } catch (error) {
          const err = (phoneLoginWithCodeResult?.error?.networkError as any)?.result?.errors[0]
            .message;
          message.error(err);
          console.log(err, error);
          return;
        }
      }
      if (type === 'forgetPassword') {
        const params = {
          phone: (values as any).mobile,
          password: (values as any).forgetpassword,
          // 'VXNlcjoxNw==' 要发送验证码才能打开选项暂时先默认这个 因为那个接口会频繁就无法调用
          id: SelectedRole || 'VXNlcjoyOA==',
          verifyCode: (values as any).captcha,
        };
        console.log(params);
        // try {
        const res = await ResetPassword({
          variables: {
            input: params,
          },
        });
        if (res?.data.userResetPassword) {
          message.success('重置成功');
        }

        // } catch (error) {
        //   console.log('验证码错误');
        // }
        // msg = await handleResetPassword({
        //   ...values,
        //   type,
        // });
        // if (msg.userResetPassword) {
        //   const defaultLoginSuccessMessage = '密码重置成功！';
        //   message.success(defaultLoginSuccessMessage);
        // }
      }
      console.log(type, msg);

      // return;
      // 登录 mock的
      msg = await login({
        ...values,
        type,
      });

      if (msg.status === 'ok') {
        const defaultLoginSuccessMessage = '登录成功！';
        message.success(defaultLoginSuccessMessage);
        const loginTime = moment(new Date()).format('YYYY/MM/DD HH:mm');
        localStorage.setItem('loginTime', loginTime);
        await fetchUserInfoMock();
        /** 此方法会跳转到 redirect 参数所在的位置 */
        if (!history) return;
        const { query } = history.location;
        const { redirect } = query as {
          redirect: string;
        };
        if (roleType === 2) {
          history.push('/user/firstlogin');
        } else {
          dispatch({
            type: 'user/setUserInfo',
            payload: {
              role: roleType,
            },
          });
          history.push(redirect || '/');
        }
        return;
      }
      console.log(msg);
      // 如果失败去设置用户错误信息
      setUserLoginState(msg);
    } catch (error) {
      const defaultLoginFailureMessage = () => {
        switch (type) {
          case 'VERIFY_CODE': {
            return catchErrorMsg(requestLoginVerifyCodeResult);
          }
          case 'account': {
            return catchErrorMsg(LoginWithPasswordResult);
          }
          case 'forgetPassword': {
            return catchErrorMsg(ResetPasswordResult);
          }
        }
      };
      const res = defaultLoginFailureMessage();

      console.log(res, LoginWithPasswordResult);
      message.error(res ?? '网络请求失败，请重试！');

      // const defaultLoginFailureMessage = '网络请求失败，请重试！';
    }
  };
  const { status, type: loginType } = userLoginState;
  return (
    <div className={styles.main}>
      <div className={styles.container}>
        <div className={styles.content}>
          <Card style={{ borderRadius: '15px' }}>
            <LoginForm
              logo={<img alt="logo" src="/logo.png" />}
              title="95Waltz-Ai"
              initialValues={{
                autoLogin: true,
              }}
              // actions={[
              //   '其他登录方式 :',
              //   <AlipayCircleOutlined key="AlipayCircleOutlined" className={styles.icon} />,
              //   <TaobaoCircleOutlined key="TaobaoCircleOutlined" className={styles.icon} />,
              //   <WeiboCircleOutlined key="WeiboCircleOutlined" className={styles.icon} />,
              // ]}
              onFinish={async (values) => {
                await handleSubmit(values as API.LoginParams);
              }}
            >
              <Tabs activeKey={type} onChange={setType}>
                {type !== 'forgetPassword' ? (
                  <>
                    <Tabs.TabPane key="account" tab={'账户密码登录'} />
                    <Tabs.TabPane key="VERIFY_CODE" tab={'验证码登录'} />
                  </>
                ) : (
                  <Tabs.TabPane key="forgetPassword" tab={'忘记密码'} />
                )}
              </Tabs>

              {status === 'error' && loginType === 'account' && (
                <LoginMessage content={'错误的用户名和密码(admin/ant.design)'} />
              )}
              {type === 'account' && (
                <>
                  <ProFormText
                    name="username"
                    fieldProps={{
                      size: 'large',
                      prefix: <UserOutlined className={styles.prefixIcon} />,
                    }}
                    placeholder={'用户名: admin or user'}
                    rules={[
                      {
                        required: true,
                        message: '用户名是必填项！',
                      },
                    ]}
                  />
                  <ProFormText.Password
                    name="password"
                    fieldProps={{
                      size: 'large',
                      prefix: <LockOutlined className={styles.prefixIcon} />,
                    }}
                    placeholder={'密码: ant.design'}
                    rules={[
                      {
                        required: true,
                        message: '密码是必填项！',
                      },
                    ]}
                  />
                </>
              )}

              {status === 'error' && loginType === 'VERIFY_CODE' && (
                <LoginMessage content="验证码错误" />
              )}
              {type === 'VERIFY_CODE' && (
                <>
                  <ProFormText
                    fieldProps={{
                      size: 'large',
                      prefix: <MobileOutlined className={styles.prefixIcon} />,
                    }}
                    name="mobile"
                    onChange={handlePhoneChange}
                    placeholder={'请输入手机号！'}
                    rules={[
                      {
                        required: true,
                        message: '手机号是必填项！',
                      },
                      {
                        pattern: /^1\d{10}$/,
                        message: '不合法的手机号！',
                      },
                    ]}
                  />
                  <ProFormCaptcha
                    fieldProps={{
                      size: 'large',
                      prefix: <LockOutlined className={styles.prefixIcon} />,
                    }}
                    captchaProps={{
                      size: 'large',
                      style: captchaStyle,
                    }}
                    onChange={handleVerifyCodeChange}
                    placeholder={'请输入验证码！'}
                    captchaTextRender={(timing, count) => {
                      if (timing) {
                        return `${count} ${'秒后重新获取'}`;
                      }
                      return '获取验证码';
                    }}
                    phoneName="mobile"
                    name="captcha"
                    rules={[
                      {
                        required: true,
                        message: '验证码是必填项！',
                      },
                    ]}
                    onGetCaptcha={async (phoneValue) => handleVerifyCode(phoneValue, 'login')}
                  />
                </>
              )}
              {type === 'forgetPassword' && (
                <>
                  <ProFormText
                    fieldProps={{
                      size: 'large',
                      prefix: <MobileOutlined className={styles.prefixIcon} />,
                    }}
                    name="mobile"
                    placeholder={'请输入手机号！'}
                    rules={[
                      {
                        required: true,
                        message: '手机号是必填项！',
                      },
                      {
                        pattern: /^1\d{10}$/,
                        message: '不合法的手机号！',
                      },
                    ]}
                  />
                  <ProFormCaptcha
                    fieldProps={{
                      autoComplete: 'new-password',
                      size: 'large',
                      prefix: <LockOutlined className={styles.prefixIcon} />,
                    }}
                    captchaProps={{
                      size: 'large',
                      style: captchaStyle,
                    }}
                    onChange={handleVerifyCodeChange}
                    placeholder={'请输入验证码！'}
                    captchaTextRender={(timing, count) => {
                      if (timing) {
                        return `${count} ${'秒后重新获取'}`;
                      }
                      return '获取验证码';
                    }}
                    phoneName="mobile"
                    name="captcha"
                    rules={[
                      {
                        required: true,
                        message: '验证码是必填项！',
                      },
                    ]}
                    onGetCaptcha={async (phoneValue) =>
                      handleVerifyCode(phoneValue, 'resetpassword')
                    }
                  />
                  <ProFormText.Password
                    name="forgetpassword"
                    fieldProps={{
                      autoComplete: 'new-password',
                      size: 'large',
                      prefix: <LockOutlined className={styles.prefixIcon} />,
                    }}
                    placeholder={'请输入密码'}
                    rules={[
                      {
                        required: true,
                        message: '密码不少于8位, 并且必须包含两种字符',
                      },
                    ]}
                  />
                  <ProFormText.Password
                    name="againpassword"
                    fieldProps={{
                      size: 'large',
                      prefix: <LockOutlined className={styles.prefixIcon} />,
                    }}
                    placeholder={'确认密码'}
                    rules={[
                      {
                        required: true,
                        message: '密码不少于8位, 并且必须包含两种字符',
                      },
                    ]}
                  />
                </>
              )}
              {['account', 'VERIFY_CODE'].includes(type) && (
                <Radio.Group onChange={onChange} value={roleType} style={{ marginBottom: '15px' }}>
                  <Radio value={3}>老师</Radio>
                  <Radio value={1} style={{ marginLeft: '20px' }}>
                    管理员
                  </Radio>
                </Radio.Group>
              )}
              <div onClick={UserLogOut}> 退出 </div>
            </LoginForm>
            {['account', 'VERIFY_CODE'].includes(type) && (
              <div
                style={{
                  width: '450px',
                  display: 'flex',
                  justifyContent: 'center',
                }}
              >
                <div
                  style={{
                    marginBottom: 24,
                    width: '328px',
                    display: 'flex',
                    justifyContent: 'space-between',
                  }}
                >
                  <ProFormCheckbox noStyle name="autoLogin">
                    记住密码
                  </ProFormCheckbox>
                  <a
                    style={{
                      float: 'right',
                    }}
                    onClick={handleForgetPassword}
                  >
                    忘记密码 ?
                  </a>
                </div>
              </div>
            )}
            <div
              style={{
                width: '450px',
                display: 'flex',
                justifyContent: 'center',
              }}
            >
              <a
                style={{
                  textDecoration: 'underline',
                }}
              >
                {['account', 'VERIFY_CODE'].includes(type) && (
                  <span onClick={() => history.push('/user/register')}>立即注册</span>
                )}
                {type === 'forgetPassword' && <span onClick={() => setType('account')}>取消</span>}
              </a>
            </div>
          </Card>
        </div>
        {/* <Footer /> */}
        <SelectRole {...SelectRoleProps} />
      </div>
    </div>
  );
};
export default connect()(Login);
